package com.sky.interceptor;


import com.alibaba.fastjson2.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.exception.UserNotLoginException;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    //前置方式
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       // 1. 从请求头中获取token
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        log.info("管理端jwt校验，请求头中的token：{}", token);

        //2. 从redis中获取token对象
        Object empId = redisTemplate.opsForValue().get("admin_token:" + token);
        if (empId == null) {
            response.setStatus(401);
            return false;
        }

        // 3. 判断验证是否通过 通过放行 不通过返回401状态码
        try {
            // 2. 校验token令牌
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            //Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            log.info("当前员工id：{}", empId);

            //BaseContext.setCurrentId(empId);
            BaseContext.setCurrentId(Long.parseLong(empId.toString()));

            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }
}